package com.utils.parsetxt.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;

public class txtUtil {
    /**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public String txtString(File file){
        String result = "";
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
            	if(s.startsWith("#")){
            		s = "";
            	}
            	if(!s.equals("")){
            		if("".equals(result)){
            			result = s;
            		}else{
            			result = result + "\n" + s;
                	}
                }
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 扫描时读取txt文件内容
     * @param filepath
     */
    public void readTxt(String filepath) {
    	FileInputStream fis = null;
    	Scanner scanner = null;
		try {
			fis = new FileInputStream(new File(filepath));
			scanner= new Scanner(fis);
			String line = "";
			
			while (scanner.hasNextLine()) {
				line = scanner.nextLine();
				System.out.println(line);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally {
			try {
				
				if(fis!=null)fis.close();
			} catch (IOException e) {
			}
			if(scanner!=null)scanner.close();
		}
    }
    
    /**
	 * 将入库的热门,趣图,短视频做个本地备份
	 * @param map
	 */
	public static void writeImage(String path, Map<String, String> hotMap) {
		
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(path, true));//追加形式
			for (String str : hotMap.keySet()) {
				if(!"".equals(str.trim())) {
					out.write(str+"\r\n");// \r\n即为换行  
					out.write(hotMap.get(str)+"\r\n"); 
				}
			}
			System.out.println("写入本地 "+path+"完毕");
		} catch (IOException e) {
			e.printStackTrace();
		}  finally {
			try {
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} // 把缓存区内容压入文件  
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			} // 最后记得关闭文件  
		}
	}
    
    public static void main(String[] args){
        File file = new File("E:/silsCodes/slis/ui/blackDecompress/extractsummary.txt");
        txtUtil t = new txtUtil();
        System.out.println(t.txtString(file));
    }
}
